package com.yjhb.android.sbz.mvp.publishtask;

import android.text.TextUtils;

import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.yjhb.android.sbz.BuildConfig;
import com.yjhb.android.sbz.entity.AddTask;
import com.yjhb.android.sbz.entity.Task;
import com.yjhb.android.sbz.entity.TaskStep;
import com.yjhb.android.sbz.http.HttpObserver;
import com.yjhb.android.sbz.http.HttpTool;
import com.yjhb.android.sbz.http.UploadTool;
import com.yjhb.android.sbz.manager.OSSManager;
import com.yjhb.android.sbz.mvp.ConventionPresenter;
import com.yjhb.android.sbz.tool.DataSaveTool;
import com.yjhb.android.sbz.tool.Tool;
import com.jojo.android.zxlib.interfaces.Callback;
import com.jojo.android.zxlib.tool.ZxLogTool;

import java.io.File;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 创建者 zx
 * 创建时间 2020/11/26 15:42
 */
public class PublishTaskPresenter extends ConventionPresenter<PublishTaskView> {
    private final String TAG = "PublishTaskPresenter";

    public PublishTaskPresenter(PublishTaskView publishTaskView) {
        super(publishTaskView);
    }

    @Override
    protected void onDestroy() {

    }

    /**
     * 核验数据  如果值不是预期值，设置默认值
     *
     * @param task
     */
    private void checkData(Task task) {
        if (task.getFetchType() != 1 && task.getFetchType() != 2) {
            task.setFetchType(1);
        }
    }

    /**
     * 发布任务
     *
     * @param addTask
     */
    public void publishTask(final AddTask addTask, final boolean modify) {
        if (view != null) {
            view.onWait();
        }
        checkData(addTask.getTask());
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                List<TaskStep> steps = addTask.getSteps();
                try {
                    for (TaskStep step : steps) {
                        if (step.getType() == 2 || step.getType() == 3 || step.getType() == 6) {
                            e.onNext("上传图片:" + step.getContent());
                            //如果图片为null,则直接返回
                            if (TextUtils.isEmpty(step.getContent())) {
                                e.onError(new Throwable(step.getTitle() + ": 图片不存在，请重新选择。"));
                                return;
                            }
                            //如果是http开始的字符串，代表已经上传成功，则跳过
                            if (step.getContent().startsWith("http")) continue;

                            File file = new File(step.getContent());
                            if (!file.exists()) {
                                e.onError(new Throwable(step.getTitle() + ": 图片不存在，请重新选择。"));
                                return;
                            }
                            //是否加水印
                            boolean isWatermark = false;

                            if (step.getType() == 3 || step.getType() == 6) {
                                isWatermark = true;
                            }
                            //压缩图片
                            File img = Tool.compressImage(file, isWatermark);
                            //将图片上传到文件服务器，如果是体验服务器和正式服上传到release文件夹，
                            //否则上传到test文件夹
                            String dir = null;
                            switch (DataSaveTool.getHost()) {
                                case BuildConfig.ServerURL_RELEASE:
                                case BuildConfig.ServerURL_ALPHA:
                                    dir = "imgV4/release/task";
                                    break;
                                default:
                                    dir = "imgV4/test/task";
                            }
                            PutObjectResult result = UploadTool.OSSUploadFile(img.getAbsolutePath(),
                                    dir,
                                    img.getName(), new Callback<Long[]>() {
                                        @Override
                                        public void callback(Long[] longs) {

                                        }
                                    });
                            if (result == null) {
                                e.onError(new Throwable("图片上传失败，请重试！"));
                                return;
                            }
                            if (result.getStatusCode() != 200) {
                                e.onError(new Throwable("图片上传失败，错误码：" + result.getStatusCode()+" 请重试！"));
                                return;
                            }
                            step.setContent(OSSManager.getUrl(dir,img.getName()));
                            e.onNext("上传完成:" + step.getContent());
                        }
                    }
                    e.onComplete();
                } catch (Exception ex) {
                    e.onError(new Throwable("图片上传异常，请重试！"));
                    ZxLogTool.err(ex);
                }

            }
        }).subscribeOn(Schedulers.io()) //在IO线程执行网路请求
                .observeOn(AndroidSchedulers.mainThread()) //在UI线程得到数据
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String addTask) {
                        if (view != null) {
                            view.uploadingImg();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ZxLogTool.err(e);
                        if (view != null) {
                            view.onFailure(-1, e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (view != null) {
                            view.uploadCompleteImg();
                        }
                        if (model!=null) {
                            HttpTool.request(modify ? model.updateTask(addTask) : model.addTask(addTask), new HttpObserver<String>() {
                                @Override
                                public void onResult(String data) {
                                    if (view != null) {
                                        view.onSuccess(data);
                                    }
                                }

                                @Override
                                public void onError(int code, String msg) {
                                    if (view != null) {
                                        view.onFailure(code, msg);
                                    }
                                }
                            });
                        }
                    }
                });


    }


}
